package org.bizon.dinner.common.gui;

import java.util.ArrayList;
import java.util.List;

import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import diiner.common.webaccess.Eat;

public class DinnerTableModel extends DefaultTableModel implements TableModel {

	private static final long serialVersionUID = 7657346155658540437L;
	private List<Eat> eats;

	public List<Eat> getEats() {
		return eats;
	}

	public DinnerTableModel(List<Eat> eats) {
		if (eats != null)
			this.eats = eats;
		else
			this.eats = new ArrayList<Eat>();
	}

	@Override
	public Object getValueAt(int row, int column) {
		switch (column) {
		case 0:
			return eats.get(row).getName();
		case 1:
			return eats.get(row).getPrice();
		case 2:
			return eats.get(row).getPieces();
		}

		return super.getValueAt(row, column);
	}

	private static final String[] names = { "Eat", "price", "Count" };

	@Override
	public String getColumnName(int column) {
		return names[column];
	}

	@Override
	public int getColumnCount() {
		return names.length;
	}

	@Override
	public int getRowCount() {
		return eats == null ? 0 : eats.size();
	}

	@Override
	public boolean isCellEditable(int row, int column) {
		return column == 2;
	}

	@Override
	public void setValueAt(Object aValue, int row, int column) {
		try {
			eats.get(row).setPieces(Integer.valueOf(aValue.toString()));
		} catch (NumberFormatException e) {
		}
		fireTableCellUpdated(row, column);
	}

	public Double countSumm() {
		Double res = new Double(0);
		for (Eat e : eats) {
			res += e.getPieces() * e.getPrice();
		}
		return res;
	}

    void setNewList(List<Eat> list) {
     this.eats = list;
     fireTableDataChanged();
    }

}
